package com.zzh.jdis;
/*
 * @Auther : wenrouyue
 * @Date : 2022/2/28-21:32
 */

import com.sun.deploy.cache.BaseLocalApplicationProperties;
import com.sun.xml.internal.ws.api.ha.StickyFeature;
import redis.clients.jedis.Jedis;

import javax.lang.model.element.NestingKind;
import java.util.Random;

import static com.zzh.jdis.jedisConnection.getJedisConn;

public class PhoneCode {
    public static StringBuilder getCode() {
        Random random = new Random();
        StringBuilder builder = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            builder.append(rand);
        }
        return builder;
    }

    public static Jedis saveCode(String phone, Jedis jedis) {
        String Code = getCode().toString();
        jedis.setex(phone, 300, Code);
        return jedis;
    }

    public static void verifyCode(String phone) {
        Jedis jedis = getJedisConn();
        String sendCode = phone + "-count";
        //说明第一次发送 或者小于4次发送
        if (jedis.get(phone) == null) {
            saveCode(phone, jedis);
            jedis.setex(phone + "-count", 60 * 60 * 12, "1");
            jedis.close();
            return;
        }
        if ( Integer.parseInt(jedis.get(sendCode)) < 3){
            saveCode(phone, jedis);
            jedis.incr(phone + "-count");
            jedis.close();
            return;
        }
        System.out.println("已经发送三次了");
        jedis.close();
    }

    public static void checkCode(String phone, String Code){
        Jedis jedis = getJedisConn();
        String redisCOde = jedis.get(phone);
        if (redisCOde != null){
            if (Code.equals(redisCOde)){
                System.out.println("验证成功");
            }else {
                System.out.println("验证码错误");
            }
            jedis.close();
            return;
        }
        System.out.println("请先获取验证码");
        jedis.close();
    }
    public static void main(String[] args) {
        String phone = "15579243210";
        verifyCode(phone);
        checkCode(phone,"798473");
    }
}
